package com.example.mvp.delegate;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.example.baselibrary.R;
import com.example.baselibrary.util.LKToastUtil;
import com.example.mvp.view.video.lisenter.JCameraLisenter;
import com.example.mvp.view.video.view.JCameraView;
import com.example.util.BCFinalist;
import com.example.util.MediaUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import cc.vv.lkbasecomponent.base.app.LKBaseApplication;
import cc.vv.lkbasecomponent.util.LKPermissionUtil;
import cc.vv.lklibrary.log.LogOperate;

/**
 * 视频录制
 * @author chaohaipeng  on 2018/7/20.
 */

public class VideoRecordDelegate extends BaseAppDelegate implements MediaUtils.OnLoadVideoImageListener {
    /**
     * 作用: 数据文件夹
     */
    private  final String PATH_ROOT = Environment.getExternalStorageDirectory().getPath()
            + "/Android/data/" + LKBaseApplication.getApplication().getPackageName() + "/";//缓存根目录

    private String saveBitmapPath;

    //权限申请自定义码
    private final int GET_PERMISSION_REQUEST = 100;
    private boolean granted = false;


    private String videoPath;

    @Override
    public void initWidget() {

    }

    @Override
    protected int initLayoutRes() {
        return R.layout.activity_video;
    }

    /**
     * 权限请求
     */
    public void permission(){
        JCameraView jCameraView = getView(R.id.jv_video);
        LKPermissionUtil.permission(Manifest.permission.CAMERA).request();
        boolean isCarma = LKPermissionUtil.isGranted(Manifest.permission.CAMERA);
        if (granted && isCarma) {
            jCameraView.onResume();
        }


    }

    /**
     * 重置
     */
    public  void onResume() {
        JCameraView jCameraView = getView(R.id.jv_video);
        if (jCameraView!=null){
            jCameraView.onResume();
        }
    }
    /**
     * 暂停
     */
    public void onPause() {
        JCameraView jCameraView = getView(R.id.jv_video);
        if (jCameraView!=null){
            jCameraView.onPause();
        }

    }


    /**
     * 获取权限
     */
    private void getPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            boolean sd = LKPermissionUtil.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            boolean audio = LKPermissionUtil.isGranted(Manifest.permission.RECORD_AUDIO);
            boolean camera = LKPermissionUtil.isGranted(Manifest.permission.CAMERA);
            if (sd && audio && camera) {
                granted = true;
            } else {
                //不具有获取权限，需要进行权限申请
                ActivityCompat.requestPermissions(this.getActivity(), new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.CAMERA}, GET_PERMISSION_REQUEST);

                granted = false;
            }
        }
    }

     public void initVodeoRecord(){

         JCameraView jv_video = getView(R.id.jv_video);

         /**
          * 设置视频保存路径
          */
         jv_video.setSaveVideoPath(PATH_ROOT + "video/");
         /**
          * JCameraView监听
          */
         jv_video.setJCameraLisenter(new JCameraLisenter() {
             @Override
             public void captureSuccess(Bitmap bitmap) {
             }

             @Override
             public void recordSuccess(String url) {
                 MediaUtils.getImageForVideo(url,VideoRecordDelegate.this);
                 videoPath=url;



             }
             @Override
             public void quit() {
                 /**
                  * 退出按钮
                  */
                 getActivity().finish();
             }
         });
         getPermissions();
     }
    /**
     * 获取视频文件时长
     *
     * @param uri 视频地址
     * @return
     */
    private int getVideoDuration(String uri) {
        int duration = 0;
        try {
            MediaPlayer mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(uri);
            mediaPlayer.prepare();
            duration = mediaPlayer.getDuration() / 1000;
            mediaPlayer = null;
        } catch (Exception e) {
            e.printStackTrace();
            duration = 0;
        }
        return duration;
    }

    /**
     * 将图片保存到指定路径
     *
     * @param bitmap
     */
    private File saveBitmap(Bitmap bitmap) {
        File file = null;
        //判断sd卡是否正常
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            // 获取SDCard指定目录下
//            File imagePath = PathUtil.getInstance().getImagePath();
            File imagePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
            //如果不存在，那就建立这个文件夹
            if (!imagePath.exists()) {
                imagePath.mkdirs();
            }
            // 在SDcard的目录下创建图片文,以当前时间为其命名
            file = new File(imagePath, System.currentTimeMillis() + ".jpg");
            FileOutputStream out = null;

            try {
                out = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            } catch (FileNotFoundException e) {
                LogOperate.e(e.getMessage(), e);
            }
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                LogOperate.e(e.getMessage(), e);
            }
        } else {
            LKToastUtil.showToastShort( "请检查您的sd卡是否可用");
        }
        return file;
    }

    @Override
    public void onLoadImage(File file) {
        saveBitmapPath=file.getAbsolutePath();
        /**
         * 获取视频路径
         */
        //将拍摄的视频路径回传
        Intent intent = new Intent();
        if (!TextUtils.isEmpty(videoPath)) {
            int duration=  getVideoDuration(videoPath);
            intent.putExtra(BCFinalist.PATH_VIDEO_PATH, videoPath);
            intent.putExtra(BCFinalist.PATH_VIDEO_FRIST_IMAGE, saveBitmapPath);
            intent.putExtra(BCFinalist.PATH_VIDEO_DURATION, duration);
            getActivity().setResult(BCFinalist.VIDEO_PLAY_REQUEST, intent);
            getActivity().finish();
        }
    }
}
